package com.lovo.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class AlipayUtil {
    @Value("${alipay.appId}")
    private String appId;
    @Value("${alipay.privateKey}")
    private String privateKey;
    @Value("${alipay.publicKey}")
    private String publicKey;
    @Value("${alipay.serviceUrl}")
    private String serviceUrl;
    @Value("${alipay.notifyUrl}")
    private String notifyUrl;
    @Value("${alipay.returnUrl}")
    private String returnUrl;

    /**
     * 支付宝官方提供网页支付接口
     *
     * @param id    商户订单号
     * @param price 订单总金额
     * @param title 订单标题
     * @return 支付宝官方封装的订单详细信息（包含订单信息和支付包提供的流水号等）
     */
    public String pay(String id, String price, String title) {
        AlipayClient alipayClient = new DefaultAlipayClient(serviceUrl, appId, privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setNotifyUrl(notifyUrl);
        request.setReturnUrl(returnUrl);
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", id);
        bizContent.put("total_amount", price);
        bizContent.put("subject", title);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");

        request.setBizContent(bizContent.toString());
        AlipayTradePagePayResponse response = null;
        String from = null;
        try {
            response = alipayClient.pageExecute(request);
            from = response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }

        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return from;
    }

    /**
     * 支付宝官方提供退款接口
     *
     * @param id    支付宝交易号
     * @param price 需要退款的金额
     * @param title 退款请求号(自定义，此请求号保证唯一，不唯一导致重复退款，如果调用接口失败或异常了，重试时需要保证退款请求号不能变更，防止该笔交易重复退款。)
     * @return 支付宝官方封装的退款信息（包含退款是否成功和支付宝提供的流水号等）
     */
    public String refund(String id, String price, String title) {
        AlipayClient alipayClient = new DefaultAlipayClient(serviceUrl, appId, privateKey, "json", "GBK", publicKey, "RSA2");
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", id);
        bizContent.put("refund_amount", price);
        bizContent.put("out_request_no", title);

        request.setBizContent(bizContent.toString());
        AlipayTradeRefundResponse response = null;
        String from = null;
        try {
            response = alipayClient.execute(request);
            from = response.getBody();
            Map mapTypes = JSON.parseObject(from);
            String map=mapTypes.get("alipay_trade_refund_response").toString();
            Map mapType = JSON.parseObject(map);
            for (Object obj : mapType.keySet()) {
                System.out.println("key为：" + obj + "值为：" + mapType.get(obj));
            }
            if ("Y".equals(mapType.get("fund_change"))){
                System.out.println("退款成功");
            }else {
                System.out.println("退款失败");
            }
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return from;
    }


    public String find(String id, String title) {
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "app_id", "your private_key", "json", "GBK", "alipay_public_key", "RSA2");
        AlipayTradeFastpayRefundQueryRequest request = new AlipayTradeFastpayRefundQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("trade_no", "2021081722001419121412730660");
        bizContent.put("out_request_no", "HZ01RF001");

//// 返回参数选项，按需传入
//JSONArray queryOptions = new JSONArray();
//queryOptions.add("refund_detail_item_list");
//bizContent.put("query_options", queryOptions);

        request.setBizContent(bizContent.toString());
        AlipayTradeFastpayRefundQueryResponse response = null;
        String from = null;
        try {
            response = alipayClient.execute(request);
            from = response.getBody();
        } catch (AlipayApiException e) {
            throw new RuntimeException(e);
        }
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
        return from;
    }
}
